<?php

use Phalcon\Logger as Logger,
    Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter,
    Phalcon\Events\Manager as EventsManager,
    Phalcon\Logger\Adapter\File as LoggerAdapter;

try {

    //Register an autoloader
    $loader = new \Phalcon\Loader();
    $loader->registerDirs(array(
        '../app/controllers/',
        '../app/models/',
        '../app/lib/'
    ))->register();

    //Create a DI
    $di = new Phalcon\DI\FactoryDefault();

    //Setup the view component
    $di->set('view', function(){
        $view = new \Phalcon\Mvc\View();
        $view->setViewsDir('../app/views/');
        return $view;
    });

    //Setup a base URI so that all generated URIs include the "tutorial" folder
    $di->set('url', function(){
        $url = new \Phalcon\Mvc\Url();
        $url->setBaseUri('/total/');
        return $url;
    });

    // Simple database connection to localhost
    $di->set('test', function() {
        $mongo = new MongoClient();
        return $mongo->selectDB("test");
    }, true);

    $di->set('total', function() {
        $mongo = new MongoClient();
        return $mongo->selectDB("total");
    }, true);

    $di->set('mytotal1', function(){
        $dbAdapter = new \Phalcon\Db\Adapter\Pdo\Mysql(array(
            "host" => "localhost",
            "username" => "total_u",
            "password" => "total",
            "dbname" => "total"
        ));

        $eventsManager = new EventsManager();
        $logger = new LoggerAdapter('/total/log/ap.log');
        $eventsManager->attach('db', function($event, $dbAdapter) use ($logger) {
            if ($event->getType() == 'beforeQuery') {
                $logger->log($dbAdapter->getSQLStatement(), Logger::INFO);
            }
        });
        $dbAdapter->setEventsManager($eventsManager);

        return $dbAdapter;

    });


    $di->set('mytotal2', function(){
        return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
            "host" => "localhost",
            "username" => "total_s",
            "password" => "total",
            "dbname" => "total"
        ));
    });


    $di->set('collectionManager', function(){
        return new Phalcon\Mvc\Collection\Manager();
    }, true);

    //Handle the request
    $application = new \Phalcon\Mvc\Application($di);

    echo $application->handle()->getContent();

} catch(\Phalcon\Exception $e) {
     echo "PhalconException: ", $e->getMessage();
}
